package cn.genmer.test.security.netty.nio;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @program:  文件复制
 * @description:
 * @author: Genmer
 * @create: 2021-09-04 22:15
 **/
public class Channel3 {
    public static void main(String[] args) throws IOException {


        String string1 = "/Users/genmersmbp/Documents/Codes/tmp/channel1.txt";
        String string2 = "/Users/genmersmbp/Documents/Codes/tmp/copy.txt";
        // 创建一个输出流
        FileInputStream fileInputStream = new FileInputStream(string1);
        FileOutputStream fileOutputStream = new FileOutputStream(string2);

        // 获得channel - 如果channel实例为空，会实例化一个FileChannelImpl - 方法内部一个synchronized的大括号
        FileChannel readChannel = fileInputStream.getChannel();
        FileChannel writeChannel = fileOutputStream.getChannel();

        // 创建缓冲区
        ByteBuffer byteBuffer = ByteBuffer.allocate(512);
        while (true){
            byteBuffer.clear();
            int read = readChannel.read(byteBuffer);
            System.out.println("r: " + read);
            // 表示读完
            if (read == -1){
                break;
            }

            // 将buff中的数据加入 writChannl
            byteBuffer.flip();
            writeChannel.write(byteBuffer);
        }

        System.out.println(new String(byteBuffer.array()));

        fileInputStream.close();
        fileOutputStream.close();
    }
}
